package cn.zhaoyuening.hnistalumnirecord.utils.page;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateCallback;

import java.util.List;

/**
 * 分页查询
 * 高级查询
 * @author Zhao
 *
 * @param <T>
 */
public class PageQueryHibernateCallback<T> implements HibernateCallback<List<T>> {
	
	//起始索引
	private int startIndex;
	//分页大小
	private int pageSize;
	private Object[] params;
	private String hql;
	
	@Override
	public List<T> doInHibernate(Session session) throws HibernateException{
		//1 通过hql语句，获得Query对象
		Query queryObject = session.createQuery(hql);
		//3 分页
		queryObject.setFirstResult(startIndex);
		queryObject.setMaxResults(pageSize);
		if (params != null) {
			//2 条件设置
			for (int i = 0; i < params.length; i++) {
				queryObject.setParameter(i, params[i]);
			}
		}
		//4 查询所有
		return queryObject.list();
	}

	public PageQueryHibernateCallback<T> setStartIndex(int startIndex) {
		this.startIndex = startIndex;
		return this;
	}
	
	public PageQueryHibernateCallback<T> setPageSize(int pageSize) {
		this.pageSize = pageSize;
		return this;
	}
	
	public PageQueryHibernateCallback<T> setParams(Object[] params) {
		this.params = params;
		return this;
	}
	
	public PageQueryHibernateCallback<T> setHql(String hql) {
		this.hql = hql;
		return this;
	}
}
